package com.cci.kangdao.service.impl;

import com.cci.kangdao.cipapi.CipServiceApi;
import com.cci.kangdao.dao.LoginDao;
import com.cci.kangdao.dao.UserTDao;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.AuthService;
import com.cci.kangdao.service.PropertiesUtils;
import com.cci.kangdao.utilTool.AESTool;
import com.cci.kangdao.utilTool.ApiErrorCode;
import com.cci.kangdao.utilTool.ParameterTool;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("authService")
public class AuthServiceImpl implements AuthService {

	private final static Logger log = Logger.getLogger(AuthServiceImpl.class);
	
	@Autowired
	private LoginDao loginDao;
	@Autowired
	private RedisClientUtils redisClientUtils;
	@Autowired
	private PropertiesUtils propertiesUtils;
	@Resource
	private UserTDao userTDao;
	@Resource
	private CipServiceApi cipServiceApi;

	@Override
	public ModelAndView getRolesList(Map<String, Object> map) {
		try{
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			HttpServletRequest request = (HttpServletRequest)map.get("request");
			JSONObject obj = new JSONObject();	
			
			String userid = request.getHeader("userid");
			userid = AESTool.decryptString(userid);//解密userid
			UserT userT = (UserT)redisClientUtils.getObject("userT"+userid);
			
			if(null == userT) {
				userT = loginDao.getUserByid(userid);
			}
			
			
			List<Map<String, Object>> rolesList = loginDao.userGroupHasRoles(userT.getUsergroupId());
			
			obj.put("status", 0);
			obj.put("msg", "");
			obj.put("list", rolesList);
			ParameterTool.writeResponse(response, obj.toString());	
		} catch(Exception e) {
			log.error(e.getMessage(),e);
		}
		
		return null;
	}

	@Override
	public ModelAndView authCheck(Map<String, Object> map) {
		try{
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			HttpServletRequest request = (HttpServletRequest)map.get("request");
			JSONObject obj = new JSONObject();	
			
			// 需要参数：分享人主键、分享角色
			String userId = "" + map.get("userId");
//			userId = AESTool.decryptString(userId);
			if(map.get("userId") == null || map.get("userId").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
				
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());	
				obj = null;
				return null;
			}
			
			Long roleId = Long.parseLong("" + map.get("roleId"));
			if(map.get("roleId") == null || map.get("roleId").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
				
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());	
				obj = null;
				return null;
			}
			
			// 验证分享信息有效性
			if(!validCheck(userId, roleId)) {
				obj.put("status", -14);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-14));
				
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());	
				return null;
			}
			
			String userid = request.getHeader("userid");
			userid = AESTool.decryptString(userid);//解密userid
			UserT userT = (UserT)redisClientUtils.getObject("userT"+userid);
			
			if(userId.equals(userid)) {
				obj.put("status", -13);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-13));
				
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());	
				return null;
			}
			
			if(null == userT) {
				userT = loginDao.getUserByid(userid);
				if(userT == null){
					obj.put("status", -3);
					obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-3));
					
					//返回客户
					ParameterTool.writeResponse(response, obj.toString());	
					obj = null;
					return null;
				}
				int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
				redisClientUtils.setObject("userT"+userT.getId(), userT, redisCacheTime);
			}
			
			// 验证当前用户是否已具有分享角色
			List<Map<String, Object>> roleList = loginDao.getUserRoles(userT.getId());
			StringBuffer sb = new StringBuffer();
			for(Map<String, Object> role: roleList) {
				if(Long.parseLong("" + role.get("ID")) == roleId) {
					obj.put("status", -12);
					obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-12));
					
					//返回客户
					ParameterTool.writeResponse(response, obj.toString());	
					obj = null;
					return null;
				} else {
					sb.append("/").append(role.get("RolesName"));
				}
			}
			
			// 返回数据：分享人相关数据信息（用户组类型，企业、服务站名称）、当前用户原有角色
			Map<String, Object> roleInfo = loginDao.getRoleInfo(roleId);
			
			// 分享人信息
			UserT user = loginDao.getUserByid(userId);
			
			
			Map<String, Object> data = new HashMap<>();
			data.put("roleId", null != roleInfo? roleId: 0);
			data.put("roleName", null != roleInfo? roleInfo.get("RolesName"): "");
			String currentRoles = sb.toString();
			data.put("currentRoles", StringUtils.isBlank(currentRoles)? "暂无角色": currentRoles.substring(1));
			data.put("userType", user.getIsType());
			data.put("companyName", StringUtils.isBlank(user.getCompanyName())? "": user.getCompanyName());
			data.put("usergroupName", StringUtils.isBlank(user.getUsergroupName())? "": user.getUsergroupName());
			data.put("usergroupSubName", StringUtils.isBlank(user.getUsergroupSubName())? "": user.getUsergroupSubName());
			data.put("stationName", StringUtils.isBlank(user.getStationName())? "": user.getStationName());
			obj.put("status", 0);
			obj.put("msg", "");
			obj.put("data", data);
			ParameterTool.writeResponse(response, obj.toString());	
		} catch(Exception e) {
			log.error(e.getMessage(),e);
		}
		return null;
	}

	@Override
	@Transactional
	public ModelAndView authChange(Map<String, Object> map) {
		try{
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			HttpServletRequest request = (HttpServletRequest)map.get("request");
			JSONObject obj = new JSONObject();	
			
			// 需要参数：分享人主键、分享角色
			String userId = "" + map.get("userId");
//			userId = AESTool.decryptString(userId);
			if(map.get("userId") == null || map.get("userId").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
				
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());	
				obj = null;
				return null;
			}
			
			Long roleId = Long.parseLong("" + map.get("roleId"));
			if(map.get("roleId") == null || map.get("roleId").toString().equals("")){
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
				
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());	
				obj = null;
				return null;
			}
			
			// 验证分享人信息有效性
			if(!validCheck(userId, roleId)) {
				obj.put("status", -14);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-14));
				
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());	
				return null;
			}
			
			String userid = request.getHeader("userid");
			userid = AESTool.decryptString(userid);//解密userid
			UserT userT = (UserT)redisClientUtils.getObject("userT"+userid);
			
			if(null == userT) {
				userT = loginDao.getUserByid(userid);
			}
			
			Long uId = userT.getId();
			
			List<Map<String, Object>> roleList = loginDao.getUserRoles(uId);
			StringBuffer sb = new StringBuffer();
			for(Map<String, Object> role: roleList) {
				sb.append("/").append(role.get("RolesName"));
			}
			
			Map<String, Object> roleInfo = loginDao.getRoleInfo(roleId);
			UserT fromUser = loginDao.getUserByid(userId);
			fromUser.setId(uId);
			fromUser.setPosition("" + roleInfo.get("RolesName")); // 职位 == 角色名称
			if(map.containsKey("wwid")) {
				fromUser.setWwid(null != map.get("wwid") && map.get("wwid").toString().trim().length() > 0? map.get("wwid") + "" : "");
			} else {
				fromUser.setWwid("");
			}
			// 修改用户信息
			loginDao.authChange(fromUser);
			
			// 解除原用户角色关联
			loginDao.delUserRoleRel("" + uId);
			
			// 修改角色信息
			map.put("uId", uId);
			loginDao.insertUserRoleByScan(map);
			int xinIsXgj = userTDao.getXgjRoleList(uId);
			UserT user = userTDao.selectById(uId);
			if(xinIsXgj > 0){
				cipServiceApi.addXgjFleetUserId(uId,user.getServiceStationID());
			}
			// 记录分享数据
			map.put("rolesPre", sb.length() > 0? sb.toString().substring(1): "暂无角色");
			map.put("rolesNow", roleInfo.get("RolesName"));
			map.put("userName", userT.getUserName());
			
			loginDao.insertScanRecord(map);
			
			obj.put("status", 0);
			obj.put("msg", "");
			ParameterTool.writeResponse(response, obj.toString());	
		} catch(Exception e) {
			log.error(e.getMessage(),e);
		}
		return null;
	}

	/**
	 * 验证分享信息有效性
	 * @param adId
	 * @param roleId
	 * @return
	 */
	public boolean validCheck(String adId, Long roleId) {
		if(null != loginDao.validCheck(adId, roleId))
			return true;
		else 
			return false;
	}
	
}
